package com.igeek.car.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.car.constant.MessageConstant;
import com.igeek.car.entity.Checi;
import com.igeek.car.entity.XianLu;
import com.igeek.car.exception.CarException;
import com.igeek.car.result.Result;
import com.igeek.car.service.CheCiService;
import com.igeek.car.vo.PageQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * TODO
 *
 * @author bbjs
 * @since 2024/12/9
 */
@RestController
@Api(tags = "调度管理接口")
@RequestMapping("/admin/checi")
@Slf4j
public class CheCiController {
    @Autowired
    private CheCiService cheCiService;

    @GetMapping("download")
    @ApiOperation("下载调度管理Excel模板")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        //1.当前项目下的模板文件
        File excelFile = null;
        try {
            excelFile = ResourceUtils.getFile("classpath:templates/diaodu模版.xlsx");
        }catch (FileNotFoundException e){
            log.error("模板文件找不到！");
            return;
        }

        if(excelFile!=null && excelFile.isFile()){
            //2.设置响应内容
            String fileName = excelFile.getName();
            response.reset();
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) excelFile.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            //3.边读边写
            byte[] bytes = new byte[1024];
            int len = 0;
            try (
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(excelFile));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ){
                while ((len=bis.read(bytes))!=-1){
                    bos.write(bytes , 0 , len);
                    bos.flush();
                }
            } catch (IOException e) {
                log.error("模板文件下载失败！");
                throw new CarException("模板文件下载失败~");
            }
        }else{
            log.error("模板文件不存在！");
        }
    }
    @ApiOperation("分页条件查询调度")
    @GetMapping("findPage")
    public Result findPage(@ApiParam("分页参数") PageQueryVO vo){
        Page<Checi> page = cheCiService.findPage(vo);
        if(page != null){
            return new Result(true, MessageConstant.QUERY_XIANLU_SUCCESS, page);
        }
        return new Result(false, MessageConstant.QUERY_XIANLU_FAIL);
    }
    @ApiOperation("新增调度")
    @PostMapping("add")
    public Result add(@RequestBody Checi checi){
        boolean flag = cheCiService.save(checi);
        if(flag){
            return new Result(true, MessageConstant.ADD_XIANLU_SUCCESS);
        }
        return new Result(false, MessageConstant.ADD_XIANLU_FAIL);
    }
    //    @ApiOperation("通过ID查询调度信息")
//    @GetMapping("{dispatch_id}")
//    public Result findOne(@PathVariable("dispatch_id") Integer id){
//        Checi checi = CheCiService.getById(id);
//        if( checi!= null){
//            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, checi);
//        }
//        return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
//    }
    @ApiOperation("编辑调度")
    @PutMapping("update")
    public Result update(@RequestBody Checi checi){
        boolean flag = cheCiService.updateById(checi);
        if(flag){
            return new Result(true, MessageConstant.UPDATE_CHECI_SUCCESS);
        }
        return new Result(false, MessageConstant.UPDATE_CHECI_SUCCESS);
    }

    @ApiOperation("删除调度")
    @DeleteMapping("{dispatch_id}")
    public Result delete(@PathVariable("dispatch_id") String dispatch_id) {
        try {
            // 调用服务层删除方法
            boolean flag = cheCiService.del(dispatch_id);

            // 根据删除结果返回成功信息或失败信息
            if (flag) {
                return new Result(true, MessageConstant.DELETE_CHECI_SUCCESS);
            } else {
                return new Result(false, MessageConstant.DELETE_CHECI_FAIL);
            }
        } catch (RuntimeException e) {
            // 捕获业务逻辑中的异常并返回错误信息
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            // 捕获其他未预料到的异常并返回通用错误信息
            return new Result(false, "删除调度时发生未知错误：" + e.getMessage());
        }
    }


    @ApiOperation("获取所有车次号")
    @GetMapping("dispatchIds")
    public Result getDispatchIds() {
        // 调用服务层方法获取所有车次号
        List<String> dispatchIds = cheCiService.listAllDispatchIds();
        // 检查是否获取成功
        if (CollectionUtils.isNotEmpty(dispatchIds)) {
            // 返回成功结果
            return new Result(true, MessageConstant.QUERY_CHECI_SUCCESS, dispatchIds);
        } else {
            // 返回失败结果
            return new Result(false, MessageConstant.QUERY_CHECI_FAIL);
        }
    }
    @PostMapping("/upload")
    public String uploadCheci(@RequestParam("file") MultipartFile excelFile) {
        try {
            // 调用 service 层的 upload 方法处理上传文件
            boolean result = cheCiService.upload(excelFile);
            if (result) {
                return "文件上传并处理成功！";
            } else {
                return "文件内容为空或上传失败！";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }
}
